package com.gxa.p2p.config;


import com.gxa.p2p.common.enum1.ExceptionCode;
import com.gxa.p2p.common.exception.MyException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author hao
 * @date 2021/11/3
 * @time 10:15
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestURI = httpServletRequest.getRequestURI();
        System.out.println(requestURI);
        if ("/admin/login".equals(requestURI)||"/admin/code".equals(requestURI)||"/upload/uploadImage".equals(requestURI)||"/uploads/uploadImage".equals(requestURI)||requestURI.contains("/images")||requestURI.contains("/rechargelog")||requestURI.contains("/withdrawlog")||requestURI.contains("/export")){
            return true;
        }else {
            String token = httpServletRequest.getHeader("token");
            token = token.substring(1, token.length() - 1);
            System.out.println("token"+token);
            HttpSession session = httpServletRequest.getSession();
            String sessionToken = (String) session.getAttribute("token");
            System.out.println("sessionToken"+sessionToken);
            if (token != null && token.equals(sessionToken)) {
                return true;
            } else {
                throw new MyException(ExceptionCode.WRONG_TOKEN);
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
